package com.dh.common.log.aspect;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * spring aop切面,在请求前后做相应的处理
 * 做统一的入参以及结果集的日志打印
 * @author dinghao
 *
 */
@Aspect
@Component
public class HttpAspect {

	private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

	@Pointcut("execution(public * com.dh.controller.*Controller.*(..))")
	public void log() {

	}

	@Before("log()")
	public void doBefore(JoinPoint joinPoint) {

		ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		//url
		logger.info("请求路径:url={}",request.getRequestURL());

		//method
		logger.info("请求的类型:type={}",request.getMethod());

		//ip
		logger.info("请求的ip:ip={}",request.getRemoteAddr());

		//类方法
		logger.info("请求的类和方法:class_method={}",joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

		//参数
		logger.info("入参:args={}",Arrays.asList(joinPoint.getArgs()));
	}

	@After("log()")
	public void doAfter() {
		logger.info("执行请求返回结果前,暂时无任何操作!");
	}

	@AfterReturning(pointcut = "log()",returning = "object")
	public void doAfterReturning(Object object){
		logger.info("响应回来的结果集为:response={}",object.toString());
	}

}
